package com.zhentao.controller;

import com.zhentao.config.MinioConfig;
import com.zhentao.config.Result;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.GetObjectArgs;
import io.minio.RemoveObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("tea/file")
public class FileController {

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient minioClient;

    /**
     * 文件上传
     */
    @PostMapping("upload")
    public Result<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file,
                                                  @RequestParam(value = "folder", defaultValue = "default") String folder) {
        try {
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String fileName = UUID.randomUUID().toString() + extension;
            String objectName = folder + "/" + fileName;

            // 上传到MinIO
            minioClient.putObject(
                PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(objectName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build()
            );

            // 构建文件URL
            String fileUrl = minioConfig.getUrlPrefix() + objectName;

            Map<String, Object> result = new HashMap<>();
            result.put("fileName", fileName);
            result.put("originalName", originalFilename);
            result.put("fileUrl", fileUrl);
            result.put("fileSize", file.getSize());
            result.put("contentType", file.getContentType());

            return Result.success("文件上传成功", result);
        } catch (Exception e) {
            return Result.error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 批量文件上传
     */
    @PostMapping("batchUpload")
    public Result<Map<String, Object>> batchUploadFiles(@RequestParam("files") MultipartFile[] files,
                                                        @RequestParam(value = "folder", defaultValue = "default") String folder) {
        try {
            if (files == null || files.length == 0) {
                return Result.error("文件不能为空");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("successCount", 0);
            result.put("failCount", 0);
            result.put("files", new java.util.ArrayList<Map<String, Object>>());

            for (MultipartFile file : files) {
                try {
                    if (!file.isEmpty()) {
                        // 生成唯一文件名
                        String originalFilename = file.getOriginalFilename();
                        String extension = "";
                        if (originalFilename != null && originalFilename.contains(".")) {
                            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
                        }
                        String fileName = UUID.randomUUID().toString() + extension;
                        String objectName = folder + "/" + fileName;

                        // 上传到MinIO
                        minioClient.putObject(
                            PutObjectArgs.builder()
                                .bucket(minioConfig.getBucketName())
                                .object(objectName)
                                .stream(file.getInputStream(), file.getSize(), -1)
                                .contentType(file.getContentType())
                                .build()
                        );

                        // 构建文件URL
                        String fileUrl = minioConfig.getUrlPrefix() + objectName;

                        Map<String, Object> fileInfo = new HashMap<>();
                        fileInfo.put("fileName", fileName);
                        fileInfo.put("originalName", originalFilename);
                        fileInfo.put("fileUrl", fileUrl);
                        fileInfo.put("fileSize", file.getSize());
                        fileInfo.put("contentType", file.getContentType());

                        ((java.util.List<Map<String, Object>>) result.get("files")).add(fileInfo);
                        result.put("successCount", (Integer) result.get("successCount") + 1);
                    }
                } catch (Exception e) {
                    result.put("failCount", (Integer) result.get("failCount") + 1);
                }
            }

            return Result.success("批量上传完成", result);
        } catch (Exception e) {
            return Result.error("批量上传失败：" + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping("delete")
    public Result<String> deleteFile(@RequestParam String objectName) {
        try {
            minioClient.removeObject(
                RemoveObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(objectName)
                    .build()
            );
            return Result.success("文件删除成功");
        } catch (Exception e) {
            return Result.error("文件删除失败：" + e.getMessage());
        }
    }

    /**
     * 获取文件信息
     */
    @GetMapping("info")
    public Result<Map<String, Object>> getFileInfo(@RequestParam String objectName) {
        try {
            // 这里可以添加获取文件元数据的逻辑
            Map<String, Object> fileInfo = new HashMap<>();
            fileInfo.put("objectName", objectName);
            fileInfo.put("fileUrl", minioConfig.getUrlPrefix() + objectName);
            
            return Result.success("获取文件信息成功", fileInfo);
        } catch (Exception e) {
            return Result.error("获取文件信息失败：" + e.getMessage());
        }
    }

    /**
     * 获取文件下载链接
     */
    @GetMapping("downloadUrl")
    public Result<String> getDownloadUrl(@RequestParam String objectName) {
        try {
            String downloadUrl = minioConfig.getUrlPrefix() + objectName;
            return Result.success("获取下载链接成功", downloadUrl);
        } catch (Exception e) {
            return Result.error("获取下载链接失败：" + e.getMessage());
        }
    }
}

